package logger

import (
	"log"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

// 标记开启日志文件按日期保存的方式
var (
	usageRotate bool

	LogEntry *logrus.Entry
)

// Get 获取日志实例
func Get() *logrus.Entry{
	if LogEntry != nil {
		return LogEntry
	}
	return logrus.NewEntry(logrus.StandardLogger())
}


// UseRotateLogs 设置日志按日期保存到文件
func UseRotateLogs(path string, levels []logrus.Level) {

	if usageRotate {
		return
	}
	// 设置使用标记
	usageRotate = true
	// 设置文循环格式
	writer, err := rotatelogs.New(
		path+".%Y%m%d%H", // .%Y%m%d%H%M
		rotatelogs.WithLinkName(path),
		rotatelogs.WithMaxAge(24*time.Hour),
		rotatelogs.WithRotationTime(time.Hour),
	)
	if err != nil {
		log.Printf("failed to create rotatelogs: %s", err)
		return
	}
	wm := make(lfshook.WriterMap, 0)
	for _, l := range levels {
		wm[l] = writer
	}

	logger := logrus.New()
	logger.Hooks.Add(lfshook.NewHook(wm, &logrus.JSONFormatter{}))
	LogEntry = logrus.NewEntry(logger)

}

// LogAddCurrentVersion 记录当前版本号到日志中
func LogAddCurrentVersion(version string) {
	LogEntry = LogEntry.WithField("version", version)
}
